// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { LQCollide } from "../../../lq_collide_system/lq_collide";
import Utils from "../../common/utils/Utils";
import { $, cNodePool, cSound, gameData } from "../../config/Config";
import { gameScene } from "../../view/scene/GameScene";
import ShowEnemy from "../pars/ShowEnemy";
import dianciflag from "../skills/effect/dianciflag";

const { ccclass, property } = cc._decorator;

@ccclass
export default class EnemyBase extends LQCollide {


    _HP: number = 1;
    _speed: number = 2.5;
    //当前移动的方向
    _delta: cc.Vec2 = cc.v2();
    //正被击退
    _isBackAction: boolean = false;
    //目标点
    _target_pos: cc.Vec2 = cc.v2();
    //加速度
    _add_move_speed: number = 0;
    //减速效果
    _sub_move_speed: number = 0;
    //原本的颜色
    _color: cc.Color = undefined;
    _sprNode: cc.Node = undefined;
    /**是否会被 击退*/
    _canHitBack: boolean = true;
    /**受伤cd */
    _hurt_cd: boolean = false;

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this._sprNode = this.node.getChildByName("spr");
        this._color = this._sprNode.color;
    }

    start() {

    }

    protected onEnable(): void {
        this._canHitBack = true;
        this._is_frozen = false;
        this._add_move_speed = 0;
        this._sub_move_speed = 0;
        this._isBackAction = false;
        this.node.color = this._color;
        let max = Math.floor(gameData._enemy_wave / 5);
        if (max < 1) max = 1;
        this._HP = Utils.getNumMinToMax(1, max);
        this._speed = 2.5 + gameData._enemy_wave * 0.05;
        this._speed = Math.floor(this._speed * 100) / 100;
        if (this._speed > 5) this._speed = 5;
        if (gameData._enemy_wave >= 5) this._hurt =1+ gameData._enemy_wave/5;
        if (this._hurt > 4) this._hurt = 4;
    }

    /**
     * 初始化数据
     * @param key 
     */
    initData(key: string) {
        this.node.stopAllActions();
        this._isBackAction = true;
        this._key = key;
        let position = Utils.getRadomPos(gameScene.heroCtrl.node.position, 2.1);
        this.is_enable = false;
        this.node.opacity = 0;
        cNodePool.get($.Prefab.showEnemy).then(value => {
            value.parent = this.node.parent;
            value.getComponent(ShowEnemy).initState(this._key, position);
        })
        this.node.position = position;
        cc.tween(this.node)
            .to(0.5, { opacity: 255 })
            .call(() => {
                this.is_enable = true;
                this._isBackAction = false;
                this.moveToPos();
            })
            .start();
    }

    // @ts-ignore
    public on_collide(collide: LQCollide): void {
    }

    //@ts-ignore
    public on_enter(collide: LQCollide) {
        // this.hitBackAction(collide.node.position);
        // return;
        if (collide.collide_category == 2) {
            if(!this.hurtCdTime())return;
            this._HP -= 2;
            if (this._HP <= 0) {
                this.removeSelf();
            } else {
                this.hitBackAction(collide.node.position);
            }
            this.moveFarHero();
        } else {
            if(!this.hurtCdTime())return;
            this._HP -= collide._hurt;
            if (this._HP <= 0) {
                if (collide.collide_category == 4) if (gameScene.heroCtrl._life_stealing > 0) {
                    let value = gameScene.heroCtrl._hurt * gameScene.heroCtrl._life_stealing;
                    gameScene.heroCtrl.addBlood(value);
                }
                this.judgeProp();
                gameData._kill_enemy_count++;
                this.removeSelf();
            } else {
                this.hitBackAction(collide.node.position);
                if (collide.collide_category == 4) this.frozenMoveSpeed();
            }
        }
    }

    //@ts-ignore
    public on_exit(collide: LQCollide) {
    }

    hurtCdTime() {
        if (this._hurt_cd) return false;
        this._hurt_cd = true;
        setTimeout(() => {
            this._hurt_cd = false;
        }, 400);
        return true;
    }

    _is_frozen: boolean = false;
    frozenMoveSpeed() {
        if (this._is_frozen || gameScene.heroCtrl._frozen == 0) return;
        this._sub_move_speed = -(gameScene.heroCtrl._frozen * (this._speed + this._add_move_speed));
        this._is_frozen = true;
        this.scheduleOnce(() => {
            this._sub_move_speed = 0;
            this._is_frozen = false;
        }, 3)
    }

    judgeProp() {
        // return;
        let ra = Math.random()*0.05 +  gameScene.heroCtrl._lucky;
        if (Math.random() * 1 < ra) {
            gameScene.PropRoot.propXingXing(this.node.position);
        }
    }

    removeSelf() {
        let pos = this.node.position;
        cNodePool.get($.Prefab.enemyDeathPars + this._key).then(value => {
            value.parent = gameScene.node;
            value.position = pos;
        })
        cNodePool.put(this.node);
        gameScene.startCheckEnemyCount();
        let index = Utils.getNumMinToMax(0, 2);
        cSound.playEffect($.Sound["jizhong" + index]);
    }

    update(dt) {
        if (gameScene.is_pause) return;
        if (this._isBackAction) return;
        if (this.node.getChildByName("dianciflag")) return;
        this.Genzong();
    }

    Genzong() {
        this._delta = this._target_pos.sub(this.node.position);
        if (this._delta.mag() <= 5) {
            this.moveToPos();
        }
        this._delta.normalizeSelf();
        let speed = this._speed + this._add_move_speed + this._sub_move_speed;
        var x2 = this.node.x + speed * this._delta.x;
        var y2 = this.node.y + speed * this._delta.y;
        this.node.setPosition(cc.v2(x2, y2));//设置跟踪的位置
        this.node.angle += 2;
    }

    hitBackAction(pos: cc.Vec2) {
        this.node.stopAllActions();
        cc.tween(this._sprNode)
            .to(0.2, { color: new cc.Color(255, 255, 255), opacity: 120 })
            .to(0.2, { color: this._color, opacity: 255 })
            .start()
        // if (gameData._enemy_wave >= 10 || !this._isBackAction) return;
        this._isBackAction = true;
        let dir = pos.sub(this.node.position);
        dir.normalizeSelf();
        let endPos = cc.v2(this.node.x - 20 * dir.x, this.node.y - 20 * dir.y);
        cc.tween(this.node)
            .to(0.1, { position: endPos })
            .call(() => {
                this._isBackAction = false;
            })
            .start()
    }


    moveToPos() {
        let flag = gameData._enemy_wave * 0.1 + 0.1;
        if (flag > 0.65) flag = 0.65;
        if (Math.random() * 1 < flag) {
            this._add_move_speed = 4;
            this._target_pos = Utils.getRadomPos(gameScene.heroCtrl.getPos(), 9, true);
            this.shootBullet();
            return;
        } else if (Math.random() * 1 < 0.3) {
            this._add_move_speed = 3;
        } else {
            this._add_move_speed = 0;
        }
        this._target_pos = Utils.getRadomPos(gameScene.heroCtrl.node.position, 3.5+Math.random() * gameData._enemy_wave, true);
        this.shootBullet();
    }

    moveFarHero() {
        this._add_move_speed = 3;
        this._target_pos = Utils.getRadomPos(gameScene.heroCtrl.node.position, 2.5, true);
    }

    dianCiJingMo(time: number) {
        let str = $.Prefab.skills + "effect/dianciflag";
        cNodePool.get(str).then(value => {
            value.parent = this.node;
            value.position = cc.v2();
            value.getComponent(dianciflag).initTime(time);
        })
    }

    shootBullet(count: number = 1) {
        let flag = gameData._enemy_wave * 0.05;
        if (flag > 0.65) flag = 0.65;
        if (Math.random() * 1 < flag) gameScene.enemyShootBullet(this.node.position, this._speed + this._add_move_speed);
    }

}
